package com.qfedu.service.impl;

import com.github.pagehelper.PageInfo;
import com.qfedu.dao.DriverDao;
import com.qfedu.entity.Driverinfo;
import com.qfedu.service.DriverService;
import com.qfedu.util.Constants;
import com.qfedu.util.RandomStringUtil;
import com.qfedu.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * projectName: logistics
 * author: CGY
 * time: 2020/10/6 11:17
 * description:
 */
@Service
public class DriverServiceImpl implements DriverService {
    @Autowired
    private DriverDao driverDao;

    private String prefix ="SJ";

    private String getCode(){
        String code = null;
        while(true){
            String s = RandomStringUtil.RandString(6);
            code = prefix +  s;
            Driverinfo driver = driverDao.findById(code);
            if(driver == null){
                break;
            }
        }
        return code;
    }

    @Override
    public List<Driverinfo> selectAllId() {
        List<Driverinfo> list = driverDao.findAllByState(Constants.DRIVER_STATE_FREE);
        return list;
    }


    @Override
    public Result addDriver(Driverinfo driverinfo) {
        String code = getCode();
        driverinfo.setId(code);
        driverinfo.setState(Constants.DRIVER_STATE_FREE);
        Driverinfo driver = driverDao.save(driverinfo);
        if(driver == null){
            return Result.error("添加失败");
        }
        return Result.success(driver);
    }

    @Override
    public PageInfo selectAll() {
        List<Driverinfo> list = driverDao.findAll();
        return new PageInfo(list);
    }

    @Override
    public Result selectDriverById(String id) {
        Driverinfo driver = driverDao.findById(id);
        System.out.println("driver = " + driver);
        if(driver == null){
            return Result.error("查询失败");
        }
        return Result.success(driver);
    }

    @Override
    public Result updateDriver(Driverinfo driverinfo) {
        Driverinfo driver = driverDao.save(driverinfo);
        if(driver == null){
            return Result.error("更新失败");
        }
        return Result.success(driver);
    }

    @Override
    public Result delete(String id) {
        Driverinfo driver = driverDao.findById(id);
        if(driver == null){
            return Result.error("用户不存在");
        }
        Integer row = driverDao.deleteById(id);
        if(row == 0){
            return Result.error("删除失败");
        }
        return Result.success(driver);
    }
}
